package com.cskaoyan.controller;

import com.cskaoyan.bean.bo.Weixin_Cart_zylBO.text_login;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.marketBean.AdminInfoBean;
import com.cskaoyan.bean.marketBean.InfoData;
import com.cskaoyan.bean.marketBean.LoginUserData;
import com.cskaoyan.bean.marketBean.MarketAdmin;
import com.cskaoyan.bean.vo.AdminLgoutVo;
import com.cskaoyan.config.shiroConfig.MyUsernamePasswordToken;
import com.cskaoyan.mapper.marketMapper.MarketAdminMapper;
import com.cskaoyan.mapper.marketMapper.MarketPermissionMapper;
import com.cskaoyan.mapper.marketMapper.MarketRoleMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//shiro整合之后，在做具体的开发
//响应结果都是JSON，Controller组件上我们都用@RestController注解


@RestController
@RequestMapping("admin/auth")
public class AuthController {

    @Autowired
    MarketAdminMapper adminMapper;
    @Autowired
    MarketPermissionMapper permissionMapper;
    @Autowired
    MarketRoleMapper roleMapper;

/**
     * Shiro安全框架 → 视频课程 4个课时 → 认证（登录）
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */


    @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map) {
        String username = (String)map.get("username");
        String password = (String)map.get("password");

        // 写业务
//在这里执行登录。Subject.login
        //subject只能作为局部变量，不能作为全局变量
        Subject subject = SecurityUtils.getSubject();
        try {
            //subject.login() 最终会执行 realm.dagetAuthentication
            subject.login(new MyUsernamePasswordToken(username, password,"admin"));
        }catch (Exception e){
            e.printStackTrace();
        }
        //判断是否成功
        boolean authenticated = subject.isAuthenticated();
        //可以获取session信息，也可以获取器sessionId
        Session session = subject.getSession();

        MarketAdmin primaryPrincipal = (MarketAdmin) subject.getPrincipals(                                                                                  ).getPrimaryPrincipal();


        LoginUserData loginUserData = new LoginUserData();
        AdminInfoBean adminInfo = new AdminInfoBean();
        adminInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        adminInfo.setNickName("admin123");
        loginUserData.setAdminInfo(adminInfo);
       loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");
        loginUserData.setToken((String)session.getId());
        return BaseRespVo.ok(loginUserData);
    }
    @RequiresPermissions("*")
    @PostMapping("logout")
    public AdminLgoutVo logout( ) {
        AdminLgoutVo adminLgoutVo=new AdminLgoutVo();
        adminLgoutVo.setErrmsg("成功");
        adminLgoutVo.setErrno(0);
        return adminLgoutVo;
    }


    @RequestMapping("info")
    public BaseRespVo info(String token) {

        Subject subject = SecurityUtils.getSubject();
        MarketAdmin principal = (MarketAdmin) subject.getPrincipal();
        String username = principal.getUsername();
        //开发完shiro之后，再整合
        InfoData infoData = new InfoData();
        infoData.setName(username);

        //根据primaryPrincipal做查询
        infoData.setAvatar(principal.getAvatar());
//        ArrayList<String> roles = new ArrayList<>();
//
//        roles.add("超级管理员");
        //通过ROLES_ID查询
        Integer id = principal.getId();

        //根据userid查询对应的role_ids的数组
        MarketAdmin marketAdmin = adminMapper.selectRoleIdByUserId(id);
        Integer[] roleIds = marketAdmin.getRoleIds();

        //根据role_ids的数组去market_role表中查询对应的name
        List<String> names = roleMapper.selectRolesByUserId(roleIds);

        //把name的list放到infoData中去
        infoData.setRoles(names);

//        ArrayList<String> perms = new ArrayList<>();
        //PERMISSION查
//        perms.add("*");
        //根据roleid去market_admin_permission表中查询对应的permission信息
        List<String> perms = permissionMapper.selectPermissionByRolesId(roleIds);
        infoData.setPerms(perms);

        return BaseRespVo.ok(infoData);
    }
}

